import 'package:amway_superapp_creator_plugin/analysis/zhuge_edit.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/utils/colors_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/user_icon_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

/// @descriptions: 用户信息展示页
/// @author: liya
/// @date: 2020-10-13
/// version: 1.0
class UserIconPage extends StatelessWidget {
  String _cachedIcon;
  UserIconPage(String icon){
    this._cachedIcon=icon;
  }

  @override
  Widget build(BuildContext context) {
    ScrollController _buildScrollController(UserIconVM vm) {
      ScrollController controller = new ScrollController();
      controller.addListener(() {
        if (controller.offset != 0) {
          vm.showGridShadow = true;
        } else {
          vm.showGridShadow = false;
        }
      });
      return controller;
    }

    List<Widget> _buildItemList(UserIconVM vm) {
      bool isShortPhone=false;
      if(ScreenUtil().screenHeightPx<2000){
        isShortPhone=true;
      }
      List<Widget> list = List();
      for (int i = 0; i < vm.items.length; i++) {
        list.add(GestureDetector(
          onTap: () {
            vm.setItemSelected(i);
          },
          // child: CircleAvatar(
          //   radius: ScreenUtil().setWidth(isShortPhone?30:35),
          //   backgroundColor:
          //       vm.items.elementAt(i).isSelected ? ColorUtil.fromHex('#418C96') : Colors.white,
          //   child: CircleAvatar(
          //     radius: ScreenUtil().setWidth(isShortPhone?29.5:34),
          //     backgroundImage: NetworkImage(vm.items.elementAt(i).picUrl),
          //     backgroundColor: Colors.white,
          //   ),
          // ),
          child: Container(
            width: ScreenUtil().setWidth(isShortPhone?60:70),
            height: ScreenUtil().setWidth(isShortPhone?60:70),
              padding: EdgeInsets.all(ScreenUtil().setWidth(3.5)), // borde width
              decoration: new BoxDecoration(
                color: vm.items.elementAt(i).isSelected ? ColorUtil.fromHex('#418C96') : Colors.white,// border color
                shape: BoxShape.circle,
              ),
              child: CircleAvatar(
                backgroundImage: NetworkImage(vm.items.elementAt(i).picUrl),
                backgroundColor: Colors.white,
              ),
          ),
          ),
        );
      }
      return list;
    }


    bool isShortPhone=false;
    if(ScreenUtil().screenHeightPx-ScreenUtil().statusBarHeight<1920){
      isShortPhone=true;
    }

    return BaseView<UserIconVM>(
        model: UserIconVM(api: Provider.of(context)),
        onModelReady: (model) async {
          if(_cachedIcon!=null){
            model.markCached(_cachedIcon);
          }
          model.fetchIconList();

          ZhugeEditAnalysis.editPage(EditPageType.aPage);

        },
        builder: (context, model, child) => WillPopScope(
          onWillPop: () async{
            if(model.getMainUrl()!=_cachedIcon){
              showBackDialog(context);
            }else{
              Navigator.of(context).pop();
            }
            return true;
          },
          child: Scaffold(
            bottomNavigationBar:                       Container(
              width: double.infinity,
              height: ScreenUtil().setHeight(isShortPhone?80:92),
              decoration: new BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                      color: ColorUtil.fromHex('#26000000'),
                      offset: Offset(0, -ScreenUtil().setHeight(2)),
                      blurRadius: ScreenUtil().setHeight(15))
                ],
              ),
              child: Padding(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil().setWidth(16),
                    ScreenUtil().setHeight(8),
                    ScreenUtil().setWidth(16),
                    ScreenUtil().setHeight(isShortPhone?20:34)),
                child: FlatButton(
                  onPressed: () {
                    ZhugeEditAnalysis.aPageClickFinish('专属头像页',model.getMainUrl());
                    Application.router.pop(context,model.getMainUrl());
                  },
                  color: ColorUtil.fromHex('#FF396E75'),
                  child: Center(
                    child: new Text('完成',
                        style: TextStyle(color: Colors.white)),
                  ),
                  shape: StadiumBorder(),
                ),
              ),
            ),
                appBar: PreferredSize(
                  preferredSize: Size.fromHeight(ScreenUtil().setHeight(isShortPhone?40:46)),
                  child: AppBar(
                      backgroundColor: Colors.white,
                      elevation: 0,
                      //去除阴影
                      brightness: Brightness.light,
                      //黑色状态栏
                      title: Text(
                        "个人专属A",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(20),
                            color: ColorsConfig.c_2c2c2c),
                      ),
                      centerTitle: true,

                      // }
                      leading: IconButton(
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: ColorsConfig.leftBackColor,
                          size: ScreenUtil().setHeight(25),
                        ),
                        onPressed: () {
                            if(model.getMainUrl()!=_cachedIcon){
                              showBackDialog(context);
                            }else{
                              Navigator.of(context).pop();
                            }
                        },
                      )),
                ),
                body: Container(
                  color: Colors.white,
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(
                            0,
                            ScreenUtil().setHeight(30),
                            0,
                            ScreenUtil().setWidth(3)),
                        child: Center(
                          child: Text(
                            "设置个人专属A",
                            style: TextStyle(fontSize: ScreenUtil().setSp(isShortPhone?30:36), color: ColorsConfig.c_2c2c2c),
                          ),
                        ),
                      ),
                      Center(
                        child: Text(
                          "选择一个您喜爱的个人专属头像吧！",
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(12),
                              color: Colors.grey),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(0, ScreenUtil().setWidth(isShortPhone?30:41),
                            0, ScreenUtil().setWidth(isShortPhone?30:46)),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              blurRadius: ScreenUtil()
                                  .setHeight(21),
                              color: Colors.black.withOpacity(0.3),
                            )
                          ],
                        ),
                        child: CircleAvatar(
                          radius:
                              ScreenUtil().setWidth(isShortPhone?80:120),
                          backgroundImage: NetworkImage(model.getMainUrl()!=null?model.getMainUrl():''),
                          backgroundColor: Colors.white,
                        ),
                      ),
                      Expanded(
                        child: GridView.count(
                          padding: EdgeInsets.symmetric(
                              horizontal: ScreenUtil().setWidth(34)),
                          // 创建几列
                          crossAxisCount: 4,
                          // Axis.horizontal表示横向滑动，scrollDirection: Axis.vertical表示纵向滑动
                          scrollDirection: Axis.vertical,
                          // 列之间的间距
                          crossAxisSpacing: ScreenUtil().setWidth(20),
                          // 行之间的间距
                          mainAxisSpacing: ScreenUtil().setWidth(20),
                          // 默认false 是否根据子孩子的宽高自动包裹item自身
                          shrinkWrap: true,
                          // true表示数据倒序排列 false表示顺序排列
                          reverse: false,
                          // 子孩子的比例
                          childAspectRatio: 1,
                          // 设置子孩子item,这里传入子孩子控件
                          children: _buildItemList(model),
                          controller: _buildScrollController(model),
                        ),
                      ),

                    ],
                  ),
                ),
              ),
        ));
  }
}

void showBackDialog(BuildContext context) {
  showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) {
        return CommTipDialog(
          content: '返回上一步会丢失当前已编辑信息，是否确认返回',
          confirmText: "知道了",
          confirmCallback: () {
            Navigator.of(context).pop();
          },
        );
      });
}
